# -*- coding: utf-8 -*-
import json
import logging.config
import os



class _LOG_Storage:
    is_load=False
    is_on=True

class log(object):
    """class log."""
    is_debug=False
    def __init__(self, name="main"):
        if name=="":
            name="None"
        self.logger = logging.getLogger(name)
        if not _LOG_Storage.is_load:
            self.setup()
        if self.is_debug:
            self.logger.setLevel(logging.DEBUG)
        else:
            self.logger.setLevel(logging.WARNING)

    def setup(self,conf_path = "",default_level = logging.INFO,env_key = "LOG_CONF"):
        value = os.getenv(env_key,None)
        if value:
            conf_path = value
        if conf_path=="":
            conf_path=os.path.split(os.path.realpath(__file__))[0]+"/default.conf"

        if os.path.exists(conf_path):
            with open(conf_path,"r") as f:
                config = json.load(f)
                logging.config.dictConfig(config)
        else:
            logging.basicConfig(level = default_level)

        _LOG_Storage.is_load=True
    def _parse(self,*msg):
        s=[]
        for m in msg:
            if isinstance(m,(float,int,str)):
                s.append(str(m))
            else:
                s.append(repr(m))

        return " ".join(s)
    def on():
        _LOG_Storage.is_on=True
    def off():
        _LOG_Storage.is_on=False
    def error(self,*msg):
        if _LOG_Storage.is_on:
            self.logger.error(self._parse(*msg))
    def warning(self,*msg):
        if _LOG_Storage.is_on:
            self.logger.warning(self._parse(*msg))
    def info(self,*msg):
        if _LOG_Storage.is_on:
            self.logger.info(self._parse(*msg))
    def debug(self,*msg):
        if _LOG_Storage.is_on:
            self.logger.debug(self._parse(*msg))
    @classmethod
    def isdebug(cls,debug=True):
        if debug:
            cls.is_debug=True
        else:
            cls.is_debug=False

        # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        #
        # dev = logging.StreamHandler()
        # dev.setLevel(logging.INFO)
        # dev.setFormatter(formatter)
        # # logging.getLogger('').removeHandler("all")
        # logging.getLogger('').addHandler(dev)
